<template>
  <div class="container">
    <div class="left-panel">
      <div
          v-for="(type, index) in signTypes"
          :key="index"
          class="sign-type-btn"
          :class="{ active: selectedType === type.value }"
          @click="resetFormAndChangeType(type.value)"
      >
        {{ type.label }}
      </div>
    </div>

    <div class="right-panel">
      <!-- 公共表单部分 -->
      <div class="common-form">
        <div class="form-item">
          <label>{{ t('label.activityName') }}</label>
          <input
              type="text"
              v-model="formData.name"
              :placeholder="t('placeholder.enterActivityName')"
              class="compact-input"
          >
        </div>

        <div class="form-item">
          <label>{{ t('label.selectCourse') }}</label>
          <el-select
              v-model="formData.course"
              :placeholder="t('placeholder.selectCourse')"
              clearable
              @change="handleCourseChange"
              class="compact-select"
          >
            <el-option
                v-for="course in courses"
                :key="course.id"
                :label="course.name"
                :value="course.id"
            />
          </el-select>
        </div>

        <div class="form-item">
          <label>{{ t('label.selectClass') }}</label>
          <el-select
              v-model="formData.classes"
              multiple
              :placeholder="t('placeholder.selectClass')"
              :disabled="!formData.course"
              class="compact-select"
          >
            <el-option
                v-for="cls in availableClasses"
                :key="cls.id"
                :label="cls.name"
                :value="cls.id"
            />
          </el-select>
        </div>

        <div class="time-settings">
          <div class="form-item">
            <label>{{ t('label.signDuration') }}</label>
            <input
                type="number"
                v-model="formData.duration"
                min="1"
                class="compact-input"
            >
            <span class="unit">{{ t('units.minutes') }}</span>
          </div>

          <div class="form-item">
            <label>{{ t('label.allowLate') }}</label>
            <input
                type="number"
                v-model="formData.allowLate"
                min="0"
                class="compact-input"
            >
            <span class="unit">{{ t('units.minutes') }}</span>
          </div>
        </div>

        <div class="form-item">
          <label>{{ t('label.useCaptcha') }}</label>
          <el-switch v-model="formData.useCaptcha" size="small" />
          <el-button
              type="primary"
              class="publish-btn"
              @click="handlePublish"
          >
            {{ t('button.publishSignIn') }}
          </el-button>
        </div>
      </div>

      <!-- 类型特定内容 -->
      <div class="type-specific-content">
        <HandleNormalSign v-if="selectedType === '0'" />
        <HandleGestureSign ref="gestureComponent" v-if="selectedType === '1'" />
        <HandlePositionSign ref="positionComponent" v-if="selectedType === '2'" />
        <HandleQRCodeSign v-if="selectedType === '3'" :qrCodeData="qrCodeData" />
        <HandlePINSign ref="pinComponent" v-if="selectedType === '4'" />
      </div>
    </div>
  </div>
</template>

<script setup>
import {onMounted, onUnmounted, ref} from 'vue'
import {ElMessage} from 'element-plus'
import axios from 'axios'
import HandleNormalSign from "@/components/teacher/signs/handleNormalSign.vue";
import HandleGestureSign from "@/components/teacher/signs/handleDraftSign.vue";
import HandlePositionSign from "@/components/teacher/signs/handlePositionSign.vue";
import HandleQRCodeSign from "@/components/teacher/signs/handleQRCodeSign.vue";
import HandlePINSign from "@/components/teacher/signs/handlePINSign.vue";
import {useI18n} from 'vue-i18n'
import WebSocketService from '@/services/websocket.js';
import store from "@/store";

const wsService = ref(null);
const { t } = useI18n()
// 创建 API 实例
const api = axios.create({
  baseURL: store.getters.getBaseURL
})

const initWebSocket = () => {
  const userId = sessionStorage.getItem('id');
  wsService.value = new WebSocketService(userId);
};
// 添加请求和响应拦截器
api.interceptors.request.use(config => {
  const token = sessionStorage.getItem('userToken')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

api.interceptors.response.use(
    response => response,
    error => {
      if (error.response?.status === 401) {
        window.location.href = '/loginAndRegister'
      }
      return Promise.reject(error)
    }
)

// 签到类型数据
const signTypes = [
  { label: t('signType.normalSign'), value: '0' },
  { label: t('signType.draftSign'), value: '1' },
  { label: t('signType.positionSign'), value: '2' },
  { label: t('signType.QRCodeSign'), value: '3' },
  { label: t('signType.PINSign'), value: '4' }
]

const selectedType = ref('0')
const gestureComponent = ref(null)
const positionComponent = ref(null)
const pinComponent = ref(null)
const qrCodeData = ref(null);

const pollInterval = ref(null);
const pollingIntervalTime = 3000;

// 重置表单数据
const resetForm = () => {
  formData.value = {
    name: '',
    course: null,
    classes: [],
    duration: 30,
    allowLate: 10,
    useCaptcha: false
  }
  // 如果是手势签到，重置手势组件
  if (selectedType.value === '1') {
    gestureComponent.value?.resetGesture()
  }
  // 如果是签到码签到，重置签到码组件
  if (selectedType.value === '4') {
    pinComponent.value?.resetCode()
  }
}

// 切换签到类型时重置表单
const resetFormAndChangeType = (type) => {
  if (pollInterval.value) {
    clearInterval(pollInterval.value);
    pollInterval.value = null;
  }
  // 重置二维码数据
  qrCodeData.value = null;
  resetForm()
  selectedType.value = type
}

// 课程和班级数据
const courses = ref([])
const availableClasses = ref([])

// 表单数据
const formData = ref({
  name: '',
  course: null,
  classes: [],
  duration: 30,
  allowLate: 10,
  useCaptcha: false
})

// 获取课程列表
const fetchCourses = async () => {
  try {
    const pageNo = 1
    const pageSize = 15
    const response = await api.get(`/course/list?pageNo=${pageNo}&pageSize=${pageSize}`)

    if (response.data.status === 'success' && response.data.code === 200) {
      courses.value = response.data.data.list.map(course => (({
        id: course.id,
        name: course.name,
        avatar: course.avatar
      })))
    } else {
      ElMessage.error(t('error.fetchCourseFailed', { reason: response.data.info || t('error.unknown') }))
    }
  } catch (error) {
    console.error(t('log.fetchCourseError'), error)
    ElMessage.error(t('error.networkError'))
  }
}

// 获取班级列表
const fetchClassesByCourseId = async (courseId) => {
  try {
    const response = await api.get(`/sys_class/${courseId}`)

    if (response.data.status === 'success' && response.data.code === 200) {
      availableClasses.value = response.data.data.map(cls => (({
        id: cls.id,
        name: cls.name,
        cid: cls.cid,
        totals: cls.totals
      })))
    } else {
      ElMessage.error(t('error.fetchClassFailed', { reason: response.data.info || t('error.unknown') }))
    }
  } catch (error) {
    console.error(t('log.fetchClassError'), error)
    ElMessage.error(t('error.networkError'))
  }
}

// 当选择课程变化时更新可用班级
const handleCourseChange = async (courseId) => {
  formData.value.classes = []
  if (courseId) {
    await fetchClassesByCourseId(courseId)
  } else {
    availableClasses.value = []
  }
}

// 发布签到
const handlePublish = async () => {
  // 表单验证
  if (!formData.value.name) {
    ElMessage.error(t('error.requireActivityName'))
    return
  }

  if (!formData.value.course) {
    ElMessage.error(t('error.selectCourse'))
    return
  }

  if (formData.value.classes.length === 0) {
    ElMessage.error(t('error.selectAtLeastOneClass'))
    return
  }

  try {
    let additionInfo = {}

    // 如果是手势签到，获取手势图案
    if (selectedType.value === '1' ) {
      const gestureCode = sessionStorage.getItem('draft')
      console.log(gestureCode)
      if (!gestureCode) {
        ElMessage.error(t('error.drawGesture'))
        return
      }
      additionInfo = {gesture: gestureCode.split('').map(Number)}
    } else if (selectedType.value === '2') {
      if (!positionComponent.value) {
        ElMessage.error(t('error.locationComponent'))
        return
      }
      const locationInfo = positionComponent.value.getLocation()
      if (!locationInfo?.latitude || !locationInfo?.longitude || !locationInfo?.range) {
        ElMessage.error(t('error.setLocation'))
        return
      }
      additionInfo = { locationDto: locationInfo }
    } else if (selectedType.value === '4') {
      const codeValue = pinComponent.value.getCode()
      if (!codeValue) {
        ElMessage.error(t('error.enterPinCode'))
        return
      }
      additionInfo = { code: codeValue }
    }

    // 构建请求体
    const requestBody = {
      sidList: formData.value.classes,
      cid: formData.value.course,
      title: formData.value.name,
      lastTime: formData.value.duration || null,
      lateTime: formData.value.allowLate || 10,
      isVerify: formData.value.useCaptcha ? 1 : 0,
      additionInfo
    }

    // 发送请求
    const response = await api.post(`/activity/${selectedType.value}`, requestBody)

    // 处理响应
    if (response.data.status === 'success' && response.data.code === 200) {
      // 如果是二维码签到，开始轮询获取二维码
      if (selectedType.value === '3') {
        const ids = response.data.data.map(item => item.id);
        // const activityId = response.data.data[0].id;
        // 立即获取二维码数据
        const refreshTime = pollingIntervalTime / 1000;
        const openResponse = await api.get(`/activity/openRefreshCodeEvent?aidList=${ids}&refreshTime=${refreshTime}`);
        ElMessage.success('发布成功！二维码正在生成中...')
        if (openResponse.data.code === 200 && openResponse.data.status === 'success') {
          const refreshResponse = await api.get(`/activity/additionInfo/${ids[0]}/3`);
          qrCodeData.value = refreshResponse.data.data.qrcode;

          // 清除之前的轮询定时器
          if (pollInterval.value) {
            clearInterval(pollInterval.value);
          }
          // 启动新的轮询
          pollInterval.value = setInterval(async () => {
            try {
              const refreshResponse = await api.get(`/activity/additionInfo/${ids[0]}/3`);
              qrCodeData.value = refreshResponse.data.data.qrcode;
            } catch (error) {
              console.error("轮询二维码数据时出错", error);
            }
          }, pollingIntervalTime);
        }
        else {
          console.log('开启二维码错误')
          ElMessage.error(t('error.publishFailed', { reason: response.data.message || t('error.unknown') }))
        }
      }
      ElMessage.success(t('success.publishSuccess'))
    } else {
      console.log('发送请求错误')
      ElMessage.error(t('error.publishFailed', { reason: response.data.message || t('error.unknown') }))
    }
  } catch (error) {
    console.error(t('log.publishError'), error)
    ElMessage.error(t('error.networkError'))
  }
}

const notification = {
  type: 'signInNotification',
  title: '签到通知',
  courseName: formData.value.name,
  lastTime: formData.value.duration,
  lateTime: formData.value.allowLate,
  isVerify: formData.value.useCaptcha ? 1 : 0,
  senderId: sessionStorage.getItem('id')
};
if (wsService.value && wsService.value.socket && wsService.value.socket.readyState === WebSocket.OPEN) {
  wsService.value.sendMessage(notification);
  ElMessage.success(t('success.publishSuccess'));
} else {
  console.error('WebSocket connection is not open');
}

// 组件挂载
onMounted(() => {
  fetchCourses();
  initWebSocket();
})

onUnmounted(() => {
  if (wsService.value && wsService.value.socket) {
    wsService.value.close();
  }
  if (pollInterval.value) {
    clearInterval(pollInterval.value);
  }
});
</script>

<style scoped>
.container {
  display: flex;
  width: 100%;
  height: 100%;
  max-width: 1200px;
  margin: 0 auto;
  background: #fff;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1);
  font-size: 14px;
}

.left-panel {
  width: 22%;
  background: #f5f7fa;
  padding: 1vh 0;
}

.sign-type-btn {
  padding: 1.2vh 0.8vw;
  margin: 0.6vh 0.8vw;
  cursor: pointer;
  border-radius: 3px;
  transition: all 0.2s;
  font-size: 13px;
}

.sign-type-btn:hover {
  background: #e4e7ed;
}

.sign-type-btn.active {
  background: #409eff;
  color: white;
}

.right-panel {
  flex: 1;
  padding: 1.5vh 1.5vw;
}

.common-form {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 1.5vh;
}

.form-item {
  display: flex;
  align-items: center;
  margin: 0.8vh 0;
  position: relative;
}

.form-item label {
  width: 100px;
  text-align: right;
  margin-right: 0.8vw;
  font-size: 13px;
}

.compact-select {
  flex: 1;
  width: 100%;
}

.compact-input {
  flex: 1;
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 3px;
  font-size: 13px;
  height: 28px;
}

.time-settings {
  display: flex;
  gap: 1.5vw;
}

.unit {
  margin-left: 6px;
  color: #909399;
  font-size: 12px;
}

.type-specific-content {
  margin-top: 1.5vh;
}

.publish-btn {
  position: absolute;
  right: 0;
  height: 32px;
  padding: 0 20px;
  margin-left: auto;
}

/* 小屏优化 */
@media (max-width: 900px) {
  .container {
    flex-direction: column;
    height: auto;
    border-radius: 8px;
    overflow: hidden;
  }

  .left-panel {
    width: 100%;
    padding: 1.5vh;
  }

  .right-panel {
    padding: 1.5vh;
  }

  .form-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .form-item label {
    width: 100%;
    text-align: left;
    margin-bottom: 8px;
    margin-right: 0;
  }

  .compact-input, .compact-select {
    width: 100%;
  }

  .time-settings {
    flex-direction: column;
    gap: 10px;
  }

  .publish-btn {
    position: static;
    width: 100%;
    margin-top: 15px;
  }
}

/* 超小屏进一步优化 */
@media (max-width: 480px) {
  .container {
    padding: 10px;
    box-sizing: border-box;
  }

  .form-item {
    margin: 10px 0;
  }

  .compact-input, .compact-select {
    height: 36px;
    font-size: 14px;
  }
}
</style>